package com.fintech.common.util;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonUtil {
	/**
	 * JSON瀛楃涓茶浆鎹㈡垚瀵硅薄
	 * 
	 * @param jsonString
	 *            闇�瑕佽浆鎹㈢殑瀛楃涓�
	 * @param type
	 *            闇�瑕佽浆鎹㈢殑瀵硅薄绫诲瀷
	 * @return 瀵硅薄
	 */
	@SuppressWarnings("unchecked")
	public static <T> T strConvtObj(String jsonString, Class<T> type) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		return (T) JSONObject.toBean(jsonObject, type);
	}
	
	public static JSONObject strConvertJsonObj(String str){
		return JSONObject.fromObject(str);
	}
	
	  
	 /** 
     * bean 转化为实体 
     * @param bean 
     * @return 
     */  
    public static HashMap<String,Object> beanToMap(Object bean){  
        HashMap<String,Object> map = new HashMap<String,Object>();  
        if(null == bean){  
            return map;  
        }  
        Class<?> clazz = bean.getClass();  
        BeanInfo beanInfo = null;  
        try {  
            beanInfo = Introspector.getBeanInfo(clazz);  
        } catch (IntrospectionException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();  
        for(PropertyDescriptor descriptor : descriptors){  
            String propertyName = descriptor.getName();  
            if(!"class".equals(propertyName)){  
                Method method = descriptor.getReadMethod();  
                Object result;  
                try {  
                    result = method.invoke(bean);  
                    if(null != result){  
                        map.put(propertyName, result);  
                    }else{  
                        map.put(propertyName, "");  
                    }  
                } catch (IllegalArgumentException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                } catch (IllegalAccessException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                } catch (InvocationTargetException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
            }  
        }  
        return map;  
    }  
	
	
}
